package play.modules.facebook;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.codec.digest.DigestUtils;
import play.data.parsing.UrlEncodedParser;
import play.exceptions.UnexpectedException;
import play.libs.WS;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: dallan
 */
public class Utils {
   public static Map<String,String> createMap(String... args) {
      Map<String,String> result = new HashMap<String,String>();
      for (int i = 0; i < args.length; i+= 2) {
         result.put(args[i], args[i+1]);
      }
      return result;
   }

   public static Map<String,String> array_merge(Map<String,String> map1, Map<String,String> map2) {
      Map<String,String> result = new HashMap<String,String>();
      if (map1 != null) result.putAll(map1);
      if (map2 != null) result.putAll(map2);
      return result;
   }

   public static String md5(String s) {
      return DigestUtils.md5Hex(s);
   }

   public static byte[] hash_hmac_sha256(String s, String apiSecret) {
      byte[] result = null;
      try {
          Mac mac = Mac.getInstance("HmacSHA256");
          SecretKeySpec secret = new SecretKeySpec(apiSecret.getBytes(),"HmacSHA256");
          mac.init(secret);
          result = mac.doFinal(s.getBytes());
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
      return result;
   }

   public static String http_build_query(Map<String,String> params) {
      if (params.size() == 0) {
         return "";
      }
      StringBuilder buf = new StringBuilder();
      for (String key : params.keySet()) {
         if (buf.length() > 0) {
            buf.append("&");
         }
         buf.append(WS.encode(key));
         buf.append('=');
         buf.append(WS.encode(params.get(key)));
      }
      return buf.toString();
   }

   public static Map<String,String[]> parse_str(String query) {
      try {
         return UrlEncodedParser.parseQueryString(new ByteArrayInputStream(query.getBytes("utf-8")));
      } catch (UnsupportedEncodingException e) {
         throw new UnexpectedException(e);
      }
   }

   /**
    * Convert json object to map
    * @param json to convert
    * @return json in map form
    * @throws com.google.gson.JsonParseException if the json object is not a map
    */
   public static Map<String,String> jsonToMap(JsonElement json) {
      return new Gson().fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
   }
}
